home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cbibcode.arc / DUP2.C < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-05  |  1.0 KB  |  38 lines

  1. /* dup2.c --- p 494  */
  2. #include <stdio.h>
  3. #include <io.h>
  4. main()
  5. {
  6.     int saved_handle;
  7.     char filename[81];
  8.     FILE *new_stdout;
  9.         /* Ask for filename to which stdout will be assigned */
  10.     printf("Enter filename to which stdout will be assigned:");
  11.     gets(filename);
  12.     if((new_stdout = fopen(filename, "w")) == NULL)
  13.     {
  14.         perror("fopen failed");
  15.         exit(1);
  16.     }
  17.         /* First duplicate the handle for stdout so that we can
  18.          * reset things at the end */
  19.     if((saved_handle = dup(1)) == -1)
  20.     {
  21.         perror("dup failed on handle 1!");
  22.         exit(1);
  23.      }
  24.         /* Get the handle of the new file using 'fileno' and
  25.          * assign handle 1 (stdout) to it by calling dup2 */
  26.     if(dup2(fileno(new_stdout), 1) == -1)
  27.         perror("dup2 failed to assign handle 1!");
  28.     else
  29.     {
  30.         printf("New handle for stdout is %d\n", fileno(new_stdout));
  31.         printf("Testing dup2. This should be in file: %s\n",
  32.                                 filename);
  33.                 /* flush to send output to open file */
  34.         fflush(stdout);
  35.         dup2(saved_handle, 1);
  36.         printf("Enter 'TYPE %s' to see result\n", filename);
  37.     }
  38. }